package com.knowif.backend.controller;

import com.knowif.aliOSS.enumConfig.AliOSSConfig;
import com.knowif.aliOSS.service.AliyunFileUtil;
import com.knowif.system.model.RestBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.UUID;

/**
 * @author ：Xh
 * @date ：Created in 2019/6/20 0020 21:15
 */
@RestController
@RequestMapping("/image")
public class FileUploadController {

    @Autowired
    AliyunFileUtil aliyunFileUtil;

    @Value("${OSS.config.image.defaultImage}")
    private String defaultImage;

    @PostMapping("/upload")
    public RestBean<?> updateImage(MultipartFile image){
        if(image == null || image.isEmpty()) {
            return RestBean.buildError("无法读取图片");
        }else{
            String uuid = UUID.randomUUID().toString();
            uuid = uuid.replaceAll("-", "");
            String fileName = uuid;
            String suffix ="."+ image.getOriginalFilename().substring(image.getOriginalFilename().lastIndexOf(".")+1);
            fileName = (fileName + suffix).toUpperCase();
            try {
                aliyunFileUtil.fileUpload(AliOSSConfig.ALIIMAGE_STUDENT.setFileName(fileName),image.getInputStream());
                return RestBean.buildSuccess(defaultImage+fileName);
            } catch (IOException e) {
                e.printStackTrace();
                return RestBean.buildError("系统异常");
            }
        }
    }

}
